﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using FlaUI.Core.AutomationElements;
using FlaUI.Core.Tools;
using FlaUI.UIA3;
using QQTools.Data.Enums.BlockGroup;
using QQTools.Data.Repositories.BlockGroup;
using QQTools.Utils;
using System.Windows.Media.Animation;
using QQTools.Logging;
using QQTools.Data.Models;
using QQTools.Data.Plus;
using FlaUI.Core.Definitions;

namespace QQTools.Services
{
    //  internal class BlockGroupServices
    class BlockGroupServices
    {

        private readonly BlockGroupRepository _blockGroupRepository;
        private readonly BlockGroupQQRepository _blockGroupQQRepository;
        private readonly MainForm _form;

        public BlockGroupServices(MainForm form,
            BlockGroupRepository blockGroupRepository,
            BlockGroupQQRepository blockGroupQQRepository)
        {
            _form = form;
            _blockGroupRepository = blockGroupRepository;
            _blockGroupQQRepository = blockGroupQQRepository;
        }



        public async Task Start(List<QQModel> qQList, int blockInterval, CancellationToken cancellationToken)
        {
            try
            {
                // 更新状态栏
                _form.UpdateStatusStrip("开始执行屏蔽任务");

                List<BlockGroupQQModel> blockGroupQQs = await _blockGroupQQRepository.GetAllAsync();
                // 1.遍历屏蔽人列表
                foreach (var qqItem in blockGroupQQs)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        LogManager.Info("[屏蔽群] 倒计时任务已取消");
                        break;
                    }
                    // 默认被屏蔽人的qq在线
                    bool qqIsOnline = true;
                    string blockGroupQQ = qqItem.QQ;
                    // 2.获取对应的群列表

                    // 更新UI表格:ListViewBlockGroup
                    _form.UpdateListViewBlockGroup(blockGroupQQ);
                    _form.UpdateListViewBlockGroupQQ(qqItem);

                    // 4.循环从群聊数据表中拿出一条,开始屏蔽:被屏蔽名单的qq
                    BlockGroupModel blockGroupTask = await _blockGroupRepository.GetAndLockNextBlockGroupAsync(blockGroupQQ);
                    // 获取总群数量
                    int totalGroup = await _blockGroupRepository.GetCountByQQAsync(blockGroupQQ);
                    // 默认已经屏蔽的群数量为0
                    int blockNumber = 0;
                    while (blockGroupTask != null)
                    {
                        if (cancellationToken.IsCancellationRequested)
                        {
                            LogManager.Info("[屏蔽群] 倒计时任务已取消");
                            break;
                        }
                        //// 获取已经屏蔽的群总数量
                        //int blockNumber = await _blockGroupRepository.GetSuccessCountByQQAsync(blockGroupQQ);

                        //// 更新UI表格:ListViewBlockGroup状态为屏蔽中
                        _form.UpdateListViewBlockGroup(blockGroupTask);

                        //string msg = $"[屏蔽群] QQ:{blockGroupQQ} 屏蔽群:{blockGroupTask.GroupNumber} 进度:{blockNumber}/{totalGroup}";
                        //_form.UpdateBlockGroupStatusStrip(msg);
                        //LogManager.Info(msg);

                        // 开始执行屏蔽群
                        var result = await BlockGroupMsg(blockGroupTask.GroupNumber, blockGroupQQ, cancellationToken);
                        if (result == BlockGroupResult.Success)
                        {
                            qqItem.BlockNumber++;
                            // 更新数据库:BlockGroup状态为屏蔽完成
                            await _blockGroupRepository.UpdateStatusByQQAndGroupNumberAsync(blockGroupQQ, blockGroupTask.GroupNumber, BlockGroupStatus.Success);

                            // 更新数据库:BlockGroupQQ的BlockNumber自增1
                            await _blockGroupQQRepository.IncrementBlockNumberAsync(blockGroupQQ);


                            // 更新UI表格:ListViewBlockGroup状态为屏蔽完成
                            _form.UpdateListViewBlockGroup(blockGroupTask);

                            // 更新UI表格:ListViewBlockGroupQQ
                            _form.UpdateListViewBlockGroupQQ(qqItem);

                        }
                        else if (result == BlockGroupResult.QQOffline)
                        {
                            // 设置为离线状态
                            qqIsOnline = false;
                            _form.UpdateListViewBlockGroup(blockGroupTask);
                        }
                        else
                        {

                            // 根据不同的结果处理

                            // 默认失败
                            _form.UpdateListViewBlockGroup(blockGroupTask);
                        }

                        // 获取已经屏蔽的群总数量
                        blockNumber = await _blockGroupRepository.GetSuccessCountByQQAsync(blockGroupQQ);
                        string msg = $"[屏蔽群] QQ:{blockGroupQQ} 屏蔽群:{blockGroupTask.GroupNumber} 进度:{blockNumber}/{totalGroup}";
                        // 更新状态栏
                        _form.UpdateStatusStrip(msg);


                        if (qqIsOnline == false)
                        {
                            // 如果qq离线,则跳出循环, 切换到下一个qq
                            LogManager.Info($"[屏蔽群] QQ:{blockGroupQQ} 离线退出屏蔽群, 继续下一个QQ");
                            break;
                        }

                        LogManager.Info($"{msg} 距离下一次屏蔽还剩: {blockInterval} 秒");
                        await _form.StartCountdown($"{msg} 距离下一次屏蔽还剩:", blockInterval, cancellationToken, $"{msg} 任务停止", null);
                        // 获取下一条群聊数据
                        blockGroupTask = await _blockGroupRepository.GetAndLockNextBlockGroupAsync(blockGroupQQ);

                        Console.WriteLine("屏蔽任务还在进行中...............................................");
                    }

                    blockNumber = await _blockGroupRepository.GetSuccessCountByQQAsync(blockGroupQQ);
                    string txt = $"[屏蔽群]  进度:{blockNumber}/{totalGroup}  QQ:{blockGroupQQ} 屏蔽任务已完成";
                    if (qqIsOnline == false)
                    {
                        // qq离线, 切换到下一个qq
                        txt = $"[屏蔽群] 进度:{blockNumber}/{totalGroup}  QQ:{blockGroupQQ} 离线退出屏蔽群, 继续下一个QQ";
                    }

                    LogManager.Info(txt);
                    // 更新状态栏
                    _form.UpdateStatusStrip(txt);
                }

            }
            catch (OperationCanceledException)
            {
                LogManager.Info("[屏蔽群] 任务被用户取消");
                //_form.UpdateStatusStrip("任务被用户取消");
            }
            catch (Exception ex)
            {
                LogManager.Error("[屏蔽群] 发生未处理的异常", ex);
                //_form.UpdateStatusStrip("任务发生错误，请查看日志");
            }

        }
        public static async Task<BlockGroupResult> BlockGroupMsg(string groupNumber, string qq, CancellationToken cancellationToken)
        {
            // 关闭其他无关窗口
            CloseOtherWindows();

            // 生成腾讯URL并打开浏览器
            string url = QQPlus.GenerateTencentUrl(groupUin: Convert.ToInt64(groupNumber), qqUin: qq);
            Process.Start(url);
            await Task.Delay(1000);

            int processId = QQPlus.GetQQPid(qq);
            AutomationElement groupChatWindow = null;

            for (int i = 0; i < 5; i++)
            {
                groupChatWindow = await QQPlus.GetGroupChatWindowWin32(processId);
                if (groupChatWindow != null)
                {
                    break;
                }
                await Task.Delay(200, cancellationToken);
            }

            if (groupChatWindow == null)
            {
                // 检查是否存在安全提醒窗口或添加群窗口
                if (QQPlus.CheckAndHandleSpecialWindows())
                {
                    LogManager.Error("[屏蔽群] 出现安全提醒窗口或添加群窗口");
                    return BlockGroupResult.GroupBlockedOrNotAdded;
                }

                // 检查是否离线
                if (QQPlus.CheckQQIsOffline(qq) == false)
                {
                    LogManager.Error($"[屏蔽群] QQ:{qq} 已离线");
                    return BlockGroupResult.QQOffline;
                }

                LogManager.Error("[屏蔽群] 获取群聊窗口失败");
                return BlockGroupResult.GroupNotFound;
            }

            LogManager.Info($"[屏蔽群] 成功打开群聊:{groupChatWindow?.Name}");
            // 设置群聊窗口为前台窗口
            Win32Api.SetForegroundWindow(groupChatWindow.Properties.NativeWindowHandle);

            await Task.Delay(1000);
            // 检查有没有 公告弹窗
            //if (await QQAuto.CloseNoticeDialog‌Windows(groupChatWindow)) {
            //    LogManager.Info("[屏蔽群] 出现 公告弹窗");
            //    await Task.Delay(1500);
            //}

            // 记录开始时间
            Stopwatch stopwatch = new Stopwatch(); // 创建计时器
            stopwatch.Start(); // 开始计时

            // 2. 点击设置按钮 展开设置菜单
            if (ExpandGroupSettingMenu(groupChatWindow))
            {
                LogManager.Info("[屏蔽群] 屏蔽群内消息");
                await Task.Delay(200);
                // 4. 点击菜单
                SelectTencentMenu("群消息设置", processId);
                await Task.Delay(200);
                SelectTencentMenu("屏蔽群消息", processId);
                await Task.Delay(500);
            }

            if (ExpandGroupSettingMenu(groupChatWindow))
            {
                LogManager.Info("[屏蔽群] 屏蔽群内图片");
                await Task.Delay(200);
                SelectTencentMenu("群消息设置", processId);
                await Task.Delay(200);
                SelectTencentMenu("屏蔽群内图片", processId);
                await Task.Delay(200);
            }
            await Task.Delay(500);
            // groupChatWindow.Close();
            Win32Api.CloseAllWindows("TXGuiFoundation", groupChatWindow.Name);
            LogManager.Info("[屏蔽群] 设置完成");

            // 记录结束时间
            stopwatch.Stop(); // 停止计时
            LogManager.Info($"查找操作耗时: {stopwatch.ElapsedMilliseconds} 毫秒");

            return BlockGroupResult.Success;
        }

        private static void CloseOtherWindows()
        {
            // 有多个群里会话窗口
            Win32Api.CloseAllQQWindowsEndsWith("个会话");
            // 关闭安全提醒窗口
            // 关闭提示窗口
            // 需要关闭的窗口标题数组
            string[] titles = { "安全提醒", "提示" };
            Win32Api.CloseAllQQWindows(titles);
        }


        /// <summary>
        /// 展开群设置
        /// </summary>
        public static bool ExpandGroupSettingMenu(AutomationElement mainWindow)
        {
            try
            {
                // 通过名称定位 设置按钮
                //var splitButton = mainWindow.FindFirstDescendant(
                //    cf => cf.ByControlType(ControlType.SplitButton)
                //        .And(cf.ByName("设置"))
                //);

                // 1. 找到群聊窗口
                AutomationElement splitButton = Retry.WhileNull(
                    () => mainWindow.FindFirstDescendant(
                        cf => cf.ByControlType(ControlType.SplitButton)
                            .And(cf.ByName("设置"))
                    ),
                    timeout: TimeSpan.FromSeconds(5),  // 总超时时间
                    interval: TimeSpan.FromMilliseconds(500)  // 重试间隔
                ).Result;

                if (splitButton == null)
                {
                    LogManager.Error("群设置按钮未找到");
                    return false;
                }

                // 获取元素的边界矩形
                var bounds = splitButton.BoundingRectangle;
                // 使用 Mouse 类点击绝对坐标 进行展开菜单
                mainWindow.Focus(); // 确保元素处于焦点状态
                System.Drawing.Point point = default;
                // 计算相对位置（例如：点击右侧中心）
                point.X = bounds.Right - 5;  // 向右偏移5像素
                point.Y = bounds.Top + (bounds.Height / 2); // 垂直居中
                FlaUI.Core.Input.Mouse.Click(point); // 使用绝对坐标点击
                return true;
            }
            catch (Exception ex)
            {
                LogManager.Error($"[群聊设置] 展开群里设置按钮失败, 原因:{ex.Message}");
                return false;
            }
        }



        /// <summary>
        /// 选择腾讯QQ菜单
        /// </summary>
        /// <param name="menuItemName"></param>
        public static void SelectTencentMenu1(string menuItemName)
        {

            using (var automation = new UIA3Automation())
            {

                List<IntPtr> intPtrs = Win32Api.FindAllWindows("TXGuiFoundation", "TXMenuWindow");

                if (intPtrs.Count == 0)
                {
                    LogManager.Error($"菜单项:{menuItemName} 未找到");
                    return;
                }
                LogManager.Info($"菜单项: 找到{intPtrs.Count}个 ");
                foreach (var intPtr in intPtrs)
                {
                    if (intPtr == IntPtr.Zero)
                    {
                        continue;
                    }
                    // 判断窗口是否可见
                    if (!Win32Api.IsWindowVisible(intPtr))
                    {
                        continue;
                    }

                    var contextMenu = automation.FromHandle(intPtr);
                    if (contextMenu == null)
                    {
                        continue;
                    }

                    LogManager.Info($"菜单项: {contextMenu.Name} ");
                    // 点击目标菜单项（直接或子菜单）
                    var settingsItem = contextMenu.FindFirstChild(
                        cf => cf.ByName(menuItemName).And(cf.ByControlType(ControlType.MenuItem))
                    );
                    // 等待菜单弹出
                    //var settingsItem = Retry.WhileNull(
                    //    () => contextMenu.FindFirstChild(
                    //    cf => cf.ByName(menuItemName).And(cf.ByControlType(ControlType.MenuItem))
                    //),
                    //    timeout: TimeSpan.FromSeconds(3)
                    //).Result;

                    if (settingsItem == null)
                    {
                        LogManager.Error($"菜单项:{menuItemName} 未找到");
                        continue;
                    }

                    settingsItem.Click();

                    return;
                }
            }
        }


        /// <summary>
        /// 选择腾讯QQ菜单
        /// </summary>
        /// <param name="menuItemName"></param>
        public static void SelectTencentMenu(string menuItemName, int processId)
        {

            // 1. 找到群聊窗口
            AutomationElement[] menuWindows = Retry.WhileNull(
                () => QQPlus.FindContextMenu(processId),
                timeout: TimeSpan.FromSeconds(5),  // 总超时时间
                interval: TimeSpan.FromMilliseconds(500)  // 重试间隔
            ).Result;

            if (menuWindows == null || menuWindows.Length == 0)
            {
                LogManager.Error($"菜单项1:{menuItemName} 未找到");
                return;
            }

            foreach (var contextMenu in menuWindows)
            {
                if (contextMenu == null)
                {
                    continue;
                }

                LogManager.Info($"菜单项: {contextMenu.Name} ");
                // 点击目标菜单项（直接或子菜单）
                var settingsItem = contextMenu.FindFirstChild(
                    cf => cf.ByName(menuItemName).And(cf.ByControlType(ControlType.MenuItem))
                );

                if (settingsItem == null)
                {
                    LogManager.Error($"菜单项:{menuItemName} 未找到");
                    continue;
                }

                settingsItem.Click();

                return;
            }
        }


    }
}

